package com.palm.easy;

import com.palm.easy.util.StringUtil;
import org.java_websocket.client.WebSocketClient;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.core.message.Listener;
import org.noear.solon.core.message.Message;
import org.noear.solon.core.message.Session;
import org.noear.solon.core.util.PrintUtil;
import org.noear.solon.socketd.SocketD;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AgentApp {
    public static void main(String[] args) throws IOException {
        Solon.start(AgentApp.class, args, app -> {
            app.enableWebSocketD(true);
        });

        String address = ManagerConfiguration.managerAddress();
        if(StringUtil.isEmpty(address)){
            PrintUtil.error("没有配置manager.address，请在配置文件中配置或使用启动参数--manager.address=ip:port方式指定");
            return;
        }
        String token = ManagerConfiguration.managerToken();

        String sessionAddress = "ws://" + address + "/server?token=" + token;
        PrintUtil.blueln("connect manager to: " + sessionAddress);
        Session session = SocketD.createSession(sessionAddress);

        //断线自动重连
        session.listener(new Listener() {
            @Override
            public void onOpen(Session session) {
                System.out.println(session);
            }

            @Override
            public void onMessage(Session session, Message message) throws IOException {
                // System.out.println(message);
            }

            @Override
            public void onClose(Session session) {
                WebSocketClient client = (WebSocketClient) session.real();
                if (client != null) {
                    try {
                        Thread.sleep(3000);
                        client.reconnectBlocking();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        //心跳连接
        session.sendHeartbeat();
        Utils.scheduled.scheduleWithFixedDelay(() -> {
            try {
                if (session.isValid())
                    session.sendHeartbeat();
            } catch (Throwable ex) {
                EventBus.push(ex);
            }
        }, 10, 10, TimeUnit.SECONDS);
    }
}
